# -*- coding:utf8 -*-

from django.http import HttpResponse, HttpResponseRedirect

from wanbatvapp.http.whttp import send_ok_response_with_data, send_error_response_with_message, \
    send_response_with_result, send_error_response_on_exception
from wanbatvapp.http.decorators import require_params
from wanpuzzle.models.wangwangba import Program, Wangwangshow, TimeProgram, WikiDetails, WikiList, HotRecommend
from wanbatvapp import settings

import datetime
import time
import urllib
import urllib2
import json
import os

__author__ = 'Forcs'

CONTENT_TYPE_VIDEO = 1
CONTENT_TYPE_TRAILER = 101


def get_app_version(request):
    version_name = None
    meta = request.META
    if "HTTP_ACCEPT" in meta:
        http_accept = meta["HTTP_ACCEPT"]
        accept_infos = http_accept.split(";")
        for accept_info_item in accept_infos:
            if accept_info_item.startswith("version"):
                version_name = accept_info_item.split("=")[1]
                break

    if not version_name and "HTTP_APP_VERSION" in meta:
        version_name = meta["HTTP_APP_VERSION"]

    version_code = 0
    if version_name:
        codes = version_name.split(".")
        codes.reverse()
        for index, code in enumerate(codes):
            c = int(code)
            version_code += c * (1000 ** index)

    return version_name, version_code


def get_qr(request, user_id=None):
    """
    获取微信二维码
    :param request:
    :return:
    """
    qr_io_stream = urllib.urlopen("http://121.201.14.248/wangwangba/photo_ajax.jsp?userId={}".format(user_id))
    content = qr_io_stream.read()
    content = content.replace('\r\n', '')
    content = content.replace('\t', '')
    qr_io_stream.close()

    url = None

    qr_json = json.loads(content)
    if "qrcode" in qr_json.keys():
        qr_code_obj = qr_json["qrcode"]
        if "url" in qr_code_obj.keys():
            url = "http://121.201.14.248{}".format(qr_code_obj["url"])

    if url:
        return send_ok_response_with_data({
            "statusCode": qr_io_stream.getcode(),
            "url": url
        })

    else:
        return send_error_response_with_message(message=u'获取不到二维码的url')


def _replace_item_key(item, raw_key, replaced_key):
    item[replaced_key] = item[raw_key]
    del item[raw_key]


def get_program_list(request, category='0'):
    """
    获取节目列表
    :param request:
    :param category: 栏目 0：综合；1：休闲；2：运动；3：展示
    :return:
    """

    category = int(category)
    try:
        qs = Program.objects.values("id", "url", "token").order_by("-id")
        if category > 0:
            qs = qs.filter(category=category)
        else:
            qs = qs.all()

        program_list = list()
        for item in qs:
            _replace_item_key(item, "id", "content_code")
            _replace_item_key(item, "url", "content_name")
            program_list.append(item)

        return send_ok_response_with_data({
            "list": program_list
        })
    except Program.DoesNotExist:
        return send_error_response_with_message(message=u'')


def _handle_get_show_list(request, user_id=None):

    version_name, version_code = get_app_version(request)
    if version_code >= 2000000:
        host = request.get_host()
        TEMPLATE = "http://{}/api/media/{}"
        try:
            qs = Wangwangshow.objects\
                .values("id", "title", "cover_url", "video_url", "token")\
                .filter(is_recommend=False).order_by("-id")
            result_list = list()
            for item in qs:
                result_list.append({
                    "title": item["title"],
                    "cover_url": TEMPLATE.format(host, item["cover_url"]),
                    "content_name": item["video_url"],
                    "content_code": item["token"],
                    "token": item["token"],
                    "cate_code": "205",
                })
            return send_ok_response_with_data(data={
                "list": result_list,
                "host": request.get_host()
            })
        except Exception as e:
            return send_error_response_with_message(message=e.message)

    # 老版本的数据，2.0以上不会执行
    try:
        qs = Wangwangshow.objects.values(
            "id", "wx_user_id", "wx_nickname", "video_url", "portrait_url",
            "cover_url", "date_added", "token", "like_count", "visited_count", "title", "is_recommend")\
            .order_by("-id")

        URL_TEMPLATE = "http://{}/api{}"

        if user_id is not None:
            qs = qs.filter(stb_user_id=user_id)

        host = request.get_host()

        show_list = list()
        is_first = True
        for item in qs:
            if is_first:
                is_first = False
                continue
            item["date_added"] = item["date_added"].strftime('%Y.%m.%d')
            item["cover_url"] = item["cover_url"]
            if not item["portrait_url"].startswith("http://"):
                item["portrait_url"] = URL_TEMPLATE.format(host, item["portrait_url"])
            _replace_item_key(item, "id", "content_code")
            _replace_item_key(item, "video_url", "content_name")
            show_list.append(item)

        return send_ok_response_with_data({
            "list": show_list,
            "host": host
        })

    except Wangwangshow.DoesNotExist:
        return send_error_response_with_message(message=u'')


def get_all_show_list(request):
    """
    获取全部的汪汪show
    :param request:
    :return:
    """
    return _handle_get_show_list(request)


def get_user_show_list(request, user_id=None):
    """
    获取个人的汪汪show
    :param request:
    :param user_id: 用户id
    :return:
    """
    return _handle_get_show_list(request, user_id)


def _handle_update_like_count(token, count):
    try:
        show_item = Wangwangshow.objects.get(token=token)
        token = show_item.token
        count = show_item.update_like(count)

        return send_ok_response_with_data(data={
            "token": token,
            "likeCount": count
        })
    except Wangwangshow.DoesNotExist:
        return send_error_response_with_message(message=u'无此token %s' % token)


def like(request, show_token=None):
    """
    点赞
    :param request:
    :param token:
    :return:
    """
    return _handle_update_like_count(show_token, 1)


def unlike(request, show_token=None):
    """
    取消点赞
    :param request:
    :param token:
    :return:
    """
    return _handle_update_like_count(show_token, -1)


@require_params(params=["filename", "category"], method='POST')
def add_program(request):
    """
    添加汪星人频道资源
    :param request:
    :return:
    """
    query = request.POST

    fn = query["filename"]
    timestamp = long(time.time())
    category = query["category"]

    import hashlib
    md5 = hashlib.md5()
    md5.update("{}{}{}".format(fn, category, timestamp))
    token = md5.hexdigest()

    try:
        model = Program(url=fn, timestamp=timestamp,
                        category=category, token=token)
        model.save()

        return send_ok_response_with_data({
            "id": model.id,
            "token": token
        })

    except Exception as e:
        return send_error_response_with_message(message=u'insert item %s fail' % token)


@require_params(params=["wx_user_id", "wx_nickname", "stb_user_id", "title", "video_name", "portrait_url"],
                method='POST')
def add_show(request):
    """
    添加汪汪show资源
    :param request:
    :return:
    """
    body = request.POST

    wx_user_id = body["wx_user_id"]
    wx_nickname = body["wx_nickname"]
    stb_user_id = body["stb_user_id"]
    video_url = body["video_name"]
    timestamp = long(time.time())
    import hashlib
    md5 = hashlib.md5()
    md5.update("{}{}{}".format(wx_user_id, video_url.encode("utf8"), timestamp))
    token = md5.hexdigest()

    try:
        keys = body.keys()

        model = Wangwangshow()
        model.wx_user_id = wx_user_id
        model.wx_nickname = wx_nickname
        model.stb_user_id = stb_user_id
        model.video_url = video_url
        model.token = token
        model.date_added = datetime.datetime.now()

        model.portrait_url = body["portrait_url"]
        if "cover_url" in keys:
            model.cover_url = body["cover_url"]
        if "title" in keys:
            model.title = body["title"]
        if "hot" in keys:
            model.is_recommend = bool(body["hot"])

        model.save()

        return send_ok_response_with_data({
            "id": model.id,
            "token": token
        })

    except Exception, e:
        return send_error_response_with_message(message=u'insert item %s fail' % token)


def sync_programs(request):

    io_stream = urllib.urlopen("http://121.201.14.248:8061/dogtv/getlist")
    content = io_stream.read()
    io_stream.close()

    import hashlib
    md5 = hashlib.md5()

    if content:
        json_obj = json.loads(content)
        data_list = json_obj["data"]["list"]

        length = len(data_list)
        for item in data_list:
            pass
            # t = item["timestamp"]
            # n = item["url"].replace('http://www.wanbatv.com', '')
            # c = item["category"]
            #
            # model = Program()
            # model.timestamp = t
            # model.url = n
            # model.category = c
            #
            # md5.update("{}{}{}".format(n, c, t))
            # model.token = md5.hexdigest()
            #
            # model.save()

        return send_ok_response_with_data({
            "insertCount": length
        })

    else:
        return send_error_response_with_message(message=u'data is empty')


@require_params(params=["auth_token", "auth_time"])
def get_program(request, res_token=None):
    """
    获取汪星人频道视频
    :param request:
    :param token: 视频资源唯一标识
    :return:
    """
    params = urllib.urlencode(request.GET)
    try:
        item = Program.objects.get(token=res_token)
        cdn_host = settings.WANGWANGBATV_CDN_URL
        query = request.GET
        if "flavor" in query and query["flavor"] == 'anhui':
            # 安徽cdn使用的是局方内网cdn地址
            cdn_host = "itv.100.ahct.lv1.vcache.cn/600"
        return HttpResponseRedirect("http://{}{}?{}".format(
            cdn_host, item.url, params))
    except Program.DoesNotExist:
        return send_error_response_with_message(u'无此资源 %s' % res_token)


@require_params(params=["auth_token", "auth_time"])
def get_show(request, res_token=None):
    """
    获取汪汪show视频
    :param request:
    :param token: 视频资源唯一标识
    :return:
    """
    params = urllib.urlencode(request.GET)
    try:
        item = Wangwangshow.objects.get(token=res_token)
        item.visited_count += 1
        item.save()
        return HttpResponseRedirect("http://{}{}?{}".format(
            settings.WANGWANGBATV_CDN_URL, item.video_url, params))
    except Wangwangshow.DoesNotExist:
        return send_error_response_with_message(u'无此资源 %s' % res_token)


def get_wiki_list(request):
    """
    获取百科列表
    :param request:
    :param res_token:
    :return:
    """

    version_name, version_code = get_app_version(request)
    if version_code >= 2000000:
        host = request.get_host()
        TEMPLATE = "http://%s/api/media/%s"
        try:
            qs = WikiList.objects.values("id", "title", "cover_url", "token", "is_recommend")\
                .filter(is_recommend=False).order_by("-id")
            result_list = list()
            for item in qs[:5]:
                result_list.append({
                    "title": item["title"],
                    "cover_url": TEMPLATE % (host, item["cover_url"]),
                    "token": item["token"]
                })

            return send_ok_response_with_data(data={
                "list": result_list
            })
        except Exception as e:
            return send_error_response_with_message(message=e.message)

    from main import wangwangba
    faq_contents = json.loads(wangwangba.FAQ_CONTENTS)
    faq_image = None
    faq_content_list = list()
    for faq_item in faq_contents:
        if not faq_image:
            faq_image = faq_item["image_url"]
        faq_content_list.append({"content": faq_item["content"]})

    faq = {
        "title": "FAQ",
        "cover_url": wangwangba.FAQ_COVER_URL,
        "content": {
            "image": faq_image,
            "contents": faq_content_list
        }
    }
    try:
        qs = WikiList.objects.values("title", "cover_url", "token", "is_recommend")\
            .filter(is_recommend=0)\
            .order_by("-timestamp")\
            .all()
        wiki_list = list()
        for wiki in qs:
            wiki_list.append(wiki)

        return send_ok_response_with_data(data={
            "list": wiki_list,
            "faq": faq
        })
    except WikiList.DoesNotExist as e:
        return send_error_response_with_message(message=e.message)


@require_params(['title', 'contents'], method='POST')
def add_wiki(request):
    """
    添加百科内容
    :param request:
    :return:
    """
    body = request.POST
    title = body['title']
    contents = body['contents']
    cover = ''
    if 'cover' in body.keys():
        cover = body['cover']
    timestamp = long(time.time())

    import hashlib
    md5 = hashlib.md5()
    # 先对内容进行MD5加密
    md5.update(contents.encode("utf8"))
    content_md5 = md5.hexdigest()
    # 然后再根据加密后的内容进行MD5加密生成token
    md5.update("{}{}{}".format(title.encode("utf8"), timestamp, content_md5))
    token = md5.hexdigest()

    try:
        list_item_model = WikiList()
        list_item_model.timestamp = timestamp
        list_item_model.title = title
        list_item_model.cover_url = cover
        list_item_model.token = token
        if "hot" in body:
            list_item_model.is_recommend = bool(body["hot"])
        list_item_model.save()

        contents_json = json.loads(contents, encoding='utf8')
        if isinstance(contents_json, list):
            for index, content_item in enumerate(contents_json):
                content_item_model = WikiDetails()
                content_item_model.image_url = content_item['image']
                content_item_model.content = content_item['content']
                content_item_model.token = token
                content_item_model.content_index = index
                content_item_model.save()
    except Exception as e:
        return send_error_response_with_message(message=e.message)

    return send_ok_response_with_data(data={
        "token": token,
        "md5": content_md5
    })


def get_wiki(request, wiki_token=None):
    """
    获取百科详情
    :param request:
    :param token:
    :return:
    """
    # 先从列表中查询，判断是否有要获取的百科内容
    # 更新访问次数
    try:
        wiki = WikiList.objects.get(token=wiki_token)
        wiki.visited_count += 1
        wiki.save()
    except WikiList.DoesNotExist as e:
        return send_error_response_with_message(u'无此条百科')

    # 获取百科详情内容清单
    qs = WikiDetails.objects.values("image_url", "content").filter(token=wiki_token).order_by("content_index")
    image = None
    content_list = list()
    try:
        for wiki_details in qs:
            if not image:
                image = wiki_details["image_url"]

            content_list.append({"content": wiki_details["content"]})

        return send_ok_response_with_data(data={
            "image": "http://%s/api/media/%s" % (request.get_host(), image),
            "list": content_list
        })
    except WikiDetails.DoesNotExist as e:
        return send_error_response_with_message(message=e.message)


def get_time_programs(request):

    now = datetime.datetime.now()

    try:
        qs = TimeProgram.objects.values("id", "url", "token", "time_start", "time_end")\
            .filter(time_start__lte=now, time_end__gt=now).order_by("id")

        program_list = list()
        time_end_current_list = None
        for item in qs:
            _replace_item_key(item, "id", "content_code")
            _replace_item_key(item, "url", "content_name")
            program_list.append(item)

            if not time_end_current_list:
                time_end_current_list = item["time_end"]

        try:
            next_time = TimeProgram.objects.get(time_start__gt=time_end_current_list)
            next_request = (next_time - now).microseconds
        except Exception as e:
            next_request = 30 * 60 * 1000 if program_list else 0

        return send_ok_response_with_data({
            "list": program_list,
            "next": next_request
        })

    except Exception as e:
        return send_error_response_with_message(message=u'')


require_params(params=["title", "contenttype", "token"], method="POST")
def add_hot_recommend(request):
    """
    添加热门推荐
    :param request:
    :return:
    """
    body = request.POST
    title = body["title"]
    content_type = body["contenttype"]
    token = body["token"]

    try:
        hot_rec_model = HotRecommend()
        hot_rec_model.title = title
        hot_rec_model.token = token
        hot_rec_model.content_type = content_type
        hot_rec_model.timestamp = long(time.time())
        if "coverurl" in body.keys():
            hot_rec_model.cover_url = body["coverurl"]

        hot_rec_model.save()

        return send_ok_response_with_data(data={
            "token": token
        })
    except HotRecommend.DoesNotExist as e:
        return send_error_response_with_message(message=e.message)


def get_hot_recommend_list(request):

    version_name, version_code = get_app_version(request)

    if version_code >= 2000000:
        host = request.get_host()
        TEMPLATE = "http://{}/api/media/{}"
        try:
            qs = HotRecommend.objects.values("title", "token", "cover_url", "content_type", "is_invalid")\
                .order_by("-id")\
                .filter(is_invalid=False, content_type__lt=3)
            result_list = list()
            result_list.append(
                {
                    "title": "这就是DOGTV",
                    "cover_urls": [
                        TEMPLATE.format(host, "wwb_hot_recommend_1_0.png"),
                        TEMPLATE.format(host, "wwb_hot_recommend_1_1.png")
                    ],
                    "content_type": 1,
                    "token": "1f86770a46c60285a1172570b99efa4d",
                    "cate_code": "205",
                    "content_name": "/dogtv/itsdogtv.TS",
                    "content_code": "1f86770a46c60285a1172570b99efa4d"
                }
            )

            if version_code >= 2001008:
                result_list[0]["cover_urls"] = [
                    TEMPLATE.format(host, "wwb_hot_1_0219.png")
                ]

            for item in qs[:3]:
                item = item.copy()
                if item["content_type"] == CONTENT_TYPE_VIDEO:
                    try:
                        show_model = Wangwangshow.objects.get(token=item["token"])
                        item["content_name"] = show_model.video_url
                        item["content_code"] = show_model.token
                        item["cate_code"] = "205"
                    except Exception as e:
                        pass
                else:
                    item["content_name"] = ''
                    item["content_code"] = ''
                    item["cate_code"] = "206"
                item["cover_urls"] = [TEMPLATE.format(host, item["cover_url"])]
                result_list.append(item)

            # if version_code >= 2001004:
            #     try:
            #         order_sale_act_item = HotRecommend.objects.order_by("-id")\
            #             .values("title", "token", "cover_url", "content_type", "is_invalid")\
            #             .get(is_invalid=False, content_type=3)
            #
            #         order_sale_act_item["content_name"] = ''
            #         order_sale_act_item["cover_urls"] = [TEMPLATE.format(host, order_sale_act_item["cover_url"])]
            #         result_list[1] = order_sale_act_item
            #     except Exception as e:
            #         pass

            return send_ok_response_with_data(data={
                "list": result_list
            })
        except Exception as e:
            return send_error_response_with_message(message=str(e))

    try:
        qs = HotRecommend.objects.values("title", "token", "cover_url", "content_type").order_by("-id").all()
        hot_rec_list = list()
        for hot_rec_item in qs:
            hot_rec_item["cover_urls"] = hot_rec_item["cover_url"].split(",")
            del hot_rec_item["cover_url"]
            hot_rec_list.append(hot_rec_item)

        return send_ok_response_with_data(data={
            "list": hot_rec_list
        })

    except HotRecommend.DoesNotExist as e:
        return send_error_response_with_message(message=e.message)


def get_dogtv_programs(request):
    version_name, version_code =get_app_version(request)
    if version_code >= 2000000:
        host = request.get_host()
        from wanbatvapp.settings import MEDIA_URL
        TEMPLATE = "http://{}" + MEDIA_URL + "{}"
        from wanpuzzle.models.wangwangba import Dogtv
        covers = dict()
        for index in range(6):
            covers[str(index)] = r'wwb_dogtv_%d.png' % index

        qs = Dogtv.objects.all()
        for item in qs:
            covers[str(item.position)] = item.cover_name

        if version_code >= 2001005:
            query = request.GET
            if 'flavor' in query.keys():
                flavor = query["flavor"]
                if flavor == 'anhui':
                    for index in range(4):
                        covers[str(index)] = r'wwb_dogtv_free_%d.png' % index

        return send_ok_response_with_data(data={
            "list": [
                {
                    "title": "综合",
                    "category": 0,
                    "cover_url": TEMPLATE.format(host, covers["0"]),
                }, {
                    "title": "休闲",
                    "category": 1,
                    "cover_url": TEMPLATE.format(host, covers["1"]),
                }, {
                    "title": "运动",
                    "category": 2,
                    "cover_url": TEMPLATE.format(host, covers["2"]),
                }, {
                    "title": "展示",
                    "category": 3,
                    "cover_url": TEMPLATE.format(host, covers["3"]),
                }
            ],
            "welcome": {
                "title": "DOG TV是什么",
                "cover_url": TEMPLATE.format(host, covers["4"]),
                "cate_code": "205",
                "content_name": "/dogtv/welcome.TS",
                "content_code": "1f86770a46c60285a1172570b99efa4d",
                "token": "1f86770a46c60285a1172570b99efa4d"
            },
            "faq": {
                "title": "FAQ",
                "cover_url": TEMPLATE.format(host, covers["5"]),
                "token": "cba90aa0936f84fc186e90ea0f5c5f5a"
            }
        })
    return send_error_response_with_message(message=u'该版本不支持此接口')


@require_params(["coverpath"], method="POST")
def sync_cover(request):

    import urllib
    from wanbatvapp.settings import MEDIA_ROOT

    host = "121.201.7.173:8087"
    if "srchost" in request.POST:
        host = request.POST["srchost"]

    cover_path = request.POST["coverpath"]
    try:
        filename = os.path.basename(cover_path)
        handler = urllib.urlopen("http://" + host + cover_path)
        fn = MEDIA_ROOT + "/" + filename
        saved_file = open(fn, "wb")
        saved_file.write(handler.read)
        saved_file.close()

        return send_ok_response_with_data(data={
            "filename": filename
        })
    except Exception as e:
        return send_error_response_with_message(message=u'同步封面 %s 失败' % (filename if filename else ''))


@require_params(["covers"], method="POST")
def sync_dogtv_cover(request):

    from wanbatvapp.settings import MEDIA_ROOT

    host = request.get_host()
    if "srchost" in request.POST:
        host = request.POST["srchost"]

    covers_synced = request.POST.getlist("covers")[0].split(",")
    length = len(covers_synced)
    exception_items = []
    success_items = []
    for cover_synced in covers_synced:
        cover_info = cover_synced.split("-")
        position = int(cover_info[0])
        cover_path = cover_info[1]
        try:
            file_name = os.path.basename(cover_path)
            handler = urllib.urlopen("http://" + host + cover_path)
            path = MEDIA_ROOT + "/" + file_name
            saved_file = open(path, "wb")
            saved_file.write(handler.read())
            saved_file.close()

            from wanpuzzle.models.wangwangba import Dogtv
            obj, create = Dogtv.objects.get_or_create(position=position)
            obj.cover_name = os.path.basename(file_name)
            obj.save()

            success_items.append({
                "position": position,
                "filename": cover_path,
                "path": path
            })

        except Exception as e:
            exception_items.append({
                "position": position,
                "filename": cover_path
            })
            continue

    if len(success_items) == length:
        response = send_ok_response_with_data(data={
            "list": success_items
        }, message=u'同步完成')
    else:
        response = send_error_response_with_message(
            message=u'成功同步了 %d 张封面，还有 %d 张未成功'
                    % (len(success_items), len(exception_items)),
            data={
                "successItems": success_items,
                "errorItems": exception_items
            })
    return response


def sync_content_wiki(request, is_recommend=False):

    body = request.POST

    if "imageurl" not in body:
        return send_error_response_with_message(message="缺少必要参数 imageurl")
    if "content" not in body:
        return send_error_response_with_message(message="缺少必要参数 content")

    title = body["title"]
    token = body["token"]
    cover_path = body["coverpath"]
    image_url = body["imageurl"]
    contents = body["content"]
    src_host = body["srchost"]

    def save(root, host, path):
        try:
            basename = os.path.basename(path)
            handler = urllib.urlopen("http://" + host + "/" + path)
            fn = root + "/" + basename
            saved_file = open(fn, "wb")
            saved_file.write(handler.read())
            saved_file.close()
            handler.close()
            return basename, fn
        except Exception as e:
            raise e

    filename = ''
    try:
        from wanbatvapp.settings import MEDIA_ROOT
        filename, local_name = save(MEDIA_ROOT, src_host, cover_path)
        filename, local_name = save(MEDIA_ROOT, src_host, image_url)
    except Exception as e:
        return send_error_response_with_message(message='%s 保存失败 %s' % (filename, str(e)))

    try:
        wiki_model, created = WikiList.objects.get_or_create(token=token)
        wiki_model.title = title
        wiki_model.cover_url = os.path.basename(cover_path)
        wiki_model.timestamp = time.time()
        wiki_model.is_recommend = is_recommend
        wiki_model.save()

        content_list = json.loads(contents, encoding='utf8')

        for index, content_item in enumerate(content_list):
            model, item_created = WikiDetails.objects.get_or_create(token=token, content_index=index)
            model.image_url = os.path.basename(image_url)
            model.content = \
                r'%s<p>%s</p>' % ("<h4>%s</h4>" % content_item["title"] if content_item["title"] else "",
                                  content_item["content"])
            model.save()

        return send_ok_response_with_data(data={
            "saveToken": token
        })

    except Exception as e:
        return send_error_response_with_message(message=e.message)


def sync_content_show(request, is_recommend=False):

    body = request.POST

    if "videourl" not in body:
        return send_error_response_with_message(message="缺少必要参数 videourl")

    video_url = body["videourl"]
    title = body["title"]
    token = body["token"]
    cover_path = body["coverpath"]
    src_host = body["srchost"]

    wx_user_id = "wanbatv"
    if "wxuserid" in body:
        wx_user_id = body["wxuserid"]

    wx_portrait = "http://www.wanbatv.com/t.jpg"
    if "wxportrait" in body:
        wx_portrait = body["wxportrait"]

    wx_nickname = "wanbatv"
    if "wxnickname" in body:
        wx_nickname = body["wxnickname"]

    stb_user_id = "stb_wanbatv"
    if "stb" in body:
        stb_user_id = body["stb"]

    try:
        from wanbatvapp.settings import MEDIA_ROOT
        filename = os.path.basename(cover_path)
        handler = urllib.urlopen("http://" + src_host + cover_path)
        fn = MEDIA_ROOT + "/" + filename
        if os.path.exists(fn):
            os.remove(fn)
        saved_file = open(fn, "wb")
        saved_file.write(handler.read())
        saved_file.close()
        handler.close()
    except Exception as e:
        return send_error_response_with_message(message=str(e))

    try:
        show_model, create = Wangwangshow.objects.get_or_create(token=token)
        show_model.title = title
        show_model.cover_url = os.path.basename(cover_path)
        show_model.video_url = video_url
        show_model.date_added = datetime.datetime.now()
        show_model.stb_user_id = stb_user_id
        show_model.wx_user_id = wx_user_id
        show_model.portrait_url = wx_portrait
        show_model.wx_nickname = wx_nickname
        show_model.token = token
        show_model.is_recommend = is_recommend
        show_model.save()

        return send_ok_response_with_data(data={
            "syncToken": token
        })
    except Exception as e:
        return send_error_response_with_message(message=str(e))

def sync_content_recommend(request):

    body = request.POST
    if "contenttype" not in body:
        return send_error_response_with_message(message="缺少必要参数 contenttype")

    token = body["token"]
    content_type = int(body["contenttype"])

    if content_type < 3:
        ct_cc_map = [None, "C0001", "C0002"]
        sync_result = None
        try:
            if len(ct_cc_map) > content_type:
                sync_result = SYNC_HANDLER[ct_cc_map[content_type]](request, is_recommend=True)
        except Exception as e:
            return send_error_response_with_message(message=e.message)
        if not sync_result or not hasattr(sync_result, "content"):
            return send_error_response_with_message("同步 %s 失败" % token)

        sync_result = json.loads(sync_result.content, encoding='utf8')
        if "resultCode" in sync_result and sync_result["resultCode"] == 1:
            try:
                rec_model, created = HotRecommend.objects.get_or_create(token=token)
                rec_model.content_type = content_type
                rec_model.cover_url = os.path.basename(body["coverpath"])
                rec_model.timestamp = time.time()
                rec_model.title = body["title"]
                rec_model.token = token
                rec_model.save()

                return send_ok_response_with_data(data={
                    "syncToken": token
                })
            except Exception as e:
                return send_error_response_with_message(message=e.message)
        else:
            return send_response_with_result(json.dumps(sync_result))
    else:

        try:
            cover_path = body["coverpath"]
            src_host = body["srchost"]

            from wanbatvapp.settings import MEDIA_ROOT
            filename = os.path.basename(cover_path)
            handler = urllib.urlopen("http://" + src_host + cover_path)
            fn = MEDIA_ROOT + "/" + filename
            if os.path.exists(fn):
                os.remove(fn)
            saved_file = open(fn, "wb")
            saved_file.write(handler.read())
            saved_file.close()
            handler.close()
        except Exception as e:
            return send_error_response_with_message(message=str(e))

        try:
            rec_model, created = HotRecommend.objects.get_or_create(token=token)
            rec_model.content_type = content_type
            rec_model.cover_url = os.path.basename(body["coverpath"])
            rec_model.timestamp = time.time()
            rec_model.title = body["title"]
            rec_model.token = token
            rec_model.save()

            return send_ok_response_with_data(data={
                "syncToken": token
            })
        except Exception as e:
            return send_error_response_with_message(message=e.message)

SYNC_HANDLER = {
    "C0001": sync_content_show,
    "C0002": sync_content_wiki,
    "C0003": sync_content_recommend,
}


@require_params(["token", "title", "coverpath", "srchost"], method="POST")
def sync_content(request, category=None):
    if category in SYNC_HANDLER:
        return SYNC_HANDLER[category](request)
    else:
        return send_error_response_with_message(message='栏目 %s 不正确，同步失败' % category)


@require_params(["wxuserids", "stb"], method="POST")
def journal_bind_weixin_users(request):
    from wanpuzzle.models.common import Application
    try:
        app_model = Application.objects.get(package="com.wanbatv.wangwangba")
    except Exception as e:
        return send_error_response_on_exception(e)

    body = request.POST
    post_data = dict()
    post_data["app"] = app_model.token + "_" + app_model.sign_key
    post_data["client"] = body["stb"]
    post_data["groups"] = body["wxuserids"]
    post_data["api"] = "wangwangba.journal.bind"

    from wanbatvapp.settings import MESSENGER_HOST
    req = urllib2.Request('http://%s/posthouse/binds' % MESSENGER_HOST, data=urllib.urlencode(post_data))
    res = urllib2.urlopen(req)
    content = res.read()
    res.close()
    return send_response_with_result(content)


@require_params(["mediatype", "mediasrc", "iconsrc", "mediaid", "stb",
                 "wxuserid", "wxnickname", "wxavatar", "date"],
                method="POST")
def notify_journal_add(request):
    body = request.POST
    data = {
        "src": body["mediasrc"],
        "mediaType": body["mediatype"],
        "iconSrc": body["iconsrc"],
        "avatar": body["wxavatar"],
        "uploadDate": body["date"],
        "mediaId": body["mediaid"],
    }
    date = data["uploadDate"]
    if date.find("-") < 0:
        temp_date = datetime.datetime.strptime(date, "%Y%m%d")
        data["uploadDate"] = temp_date.strftime("%Y-%m-%d")

    return _notify_result_group(request, "wangwangba.journal.add", request.POST["wxuserid"], data)


@require_params(["wxuserid", "stb"],
                method="POST")
def notify_journal_bind(request):
    from wanpuzzle.models.common import Application
    try:
        app_model = Application.objects.get(package="com.wanbatv.wangwangba")
    except Exception as e:
        return send_error_response_on_exception(e)

    body = request.POST

    import logging
    logger = logging.getLogger("wanba")

    post_data = dict()
    post_data["app"] = app_model.token + "_" + app_model.sign_key
    post_data["client"] = body["stb"]
    post_data["group"] = body["wxuserid"]
    post_data["api"] = "wangwangba.journal.bind"

    from wanbatvapp.settings import MESSENGER_HOST
    req = urllib2.Request('http://%s/posthouse/bind' % MESSENGER_HOST, data=urllib.urlencode(post_data))
    res = urllib2.urlopen(req)
    content = res.read()
    res.close()

    return send_response_with_result(content)


def _notify_result_single(request, tag=None, client=None, data=None):
    from wanpuzzle.models.common import Application
    try:
        app_model = Application.objects.get(package="com.wanbatv.wangwangba")
    except Exception as e:
        return send_error_response_on_exception(e)

    if not client:
        return send_error_response_with_message(message='缺少参数 client')

    post_data = dict()
    post_data["app"] = app_model.token + "_" + app_model.sign_key
    post_data["client"] = client
    post_data["api"] = tag
    post_data["data"] = json.dumps(data if data else request.POST.copy())

    from wanbatvapp.settings import MESSENGER_HOST
    req = urllib2.Request('http://%s/posthouse/notify/single' % MESSENGER_HOST, data=urllib.urlencode(post_data))
    res = urllib2.urlopen(req)
    content = res.read()
    res.close()

    return send_response_with_result(content)


def _notify_result_group(request, tag=None, group=None, data=None):
    from wanpuzzle.models.common import Application
    try:
        app_model = Application.objects.get(package="com.wanbatv.wangwangba")
    except Exception as e:
        return send_error_response_on_exception(e)

    if not group:
        return send_error_response_with_message(message='缺少参数 client')

    post_data = dict()
    post_data["app"] = app_model.token + "_" + app_model.sign_key
    post_data["group"] = group
    post_data["api"] = tag
    post_data["data"] = json.dumps(data if data else request.POST.copy())

    from wanbatvapp.settings import MESSENGER_HOST
    req = urllib2.Request('http://%s/posthouse/notify/group' % MESSENGER_HOST, data=urllib.urlencode(post_data))
    res = urllib2.urlopen(req)
    content = res.read()
    res.close()

    return send_response_with_result(content)


def get_trailer(request):

    # try:
    #     trailder_info = HotRecommend.objects.values("title", "cover_url")\
    #                         .order_by("-id")\
    #                         .filter(is_invalid=False, content_type=CONTENT_TYPE_TRAILER)\
    #                         .last()
    #
    # except Exception as e:
    #     return send_error_response_on_exception(e)
    host = request.get_host()
    TEMPLATE = "http://{}/api/media/{}"
    return send_ok_response_with_data({
        'title': 'DEMO TRAILER',
        'cover_url': 'http://61.191.46.245/121.201.14.248/8062/adjxtag/api/media/wwb_trailer_cover.png',
        'loop_playlist': [
            {
                'content_name': '/dogtv/DOGS4004_H264_16-9_1920x1080_2000000bps.TS',
                'token': '597b4356eebbd973b8cfeca487a50f2f'
            },
            {
                'content_name': '/dogtv/DOGS4059_H264_16-9_1920x1080_2000000bps.TS',
                'token': '33d5597fc4fe11f94b510648da2185df'
            },
            {
                'content_name': '/dogtv/DOGS4084_H264_16-9_1920x1080_2000000bps.TS',
                'token': '1a7934b66d9c29f4953701c2c101ba52'
            },
            {
                'content_name': '/dogtv/DOGS4092_H264_16-9_1920x1080_2000000bps.TS',
                'token': 'ab988d62bb9e33dde12ae2d105de3c52'
            },
            {
                'content_name': '/dogtv/DOGS4207_H264_16-9_1920x1080_2000000bps.TS',
                'token': 'ca056491aee5a56baf5e833c37498373'
            }
        ]
    })

